/*
 * Copyright 2003-2007 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

package com.colony.networkvm.instruction;

import java.io.IOException;

import com.argot.TypeException;
import com.argot.TypeLibraryWriter;
import com.argot.TypeMap;
import com.argot.TypeOutputStream;
import com.argot.TypeWriter;
import com.argot.common.BigEndianUnsignedShort;
import com.colony.networkvm.machine.NvmInstance;
import com.colony.remote.RemoteException;

public class NvmStoreHeapObject
implements NvmInstruction
{
    public static final String TYPENAME = "nvm.instruction.store_heap_object";
	
	private int _index;
	
	public NvmStoreHeapObject( int index )
	{
		_index = index;
	}
	
    public void execute(NvmInstance request) 
    throws RemoteException
    {
    	request.incProgramCounter();
    	
    	int id = request.peekId();
		Object o = request.pop();
    	if ( id == -1 )
    	{
    		try
            {
                id = request.getTypeLibrary().getId(o.getClass());
            }
            catch (TypeException e)
            {
                e.printStackTrace();
                throw new RemoteException( e.getMessage(), e );
            }
    	}
        request.storeHeapObject( _index, id, o );
        
    }

    private static class NvmStoreHeapObjectTypeWriter
    implements TypeWriter
    {
    	private TypeWriter _uint16;
    	
    	public NvmStoreHeapObjectTypeWriter(TypeMap map)
    	throws TypeException
    	{
    		_uint16 = map.getWriter(map.getId(BigEndianUnsignedShort.TYPENAME)); 
    	}
    	
	    public void write(TypeOutputStream out, Object o) throws TypeException, IOException
	    {
			NvmStoreHeapObject instruction = (NvmStoreHeapObject) o;
			int id = instruction._index;
	    	
			_uint16.write( out, new Integer(id));
	    }
    }
    
    public static class NvmStoreHeapObjectTypeLibraryWriter
    implements TypeLibraryWriter
    {
		public TypeWriter getWriter(TypeMap map) 
		throws TypeException 
		{
			return new NvmStoreHeapObjectTypeWriter(map);
		}
    	
    }

}
